package com.example.pkmedical.Activity.weight.weightdevice;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

import com.example.pkmedical.APP.MyApp;
import com.example.pkmedical.Activity.weight.options.OptionAddContinueActivity;
import com.example.pkmedical.Activity.weight.tozero.ReleaseZeroActivity;
import com.example.pkmedical.Activity.weight.tozero.ReleaseZeroNextActivity;
import com.example.pkmedical.Base.BaseActivity;
import com.example.pkmedical.DB.WeightData;
import com.example.pkmedical.DB.WeightData_Table;
import com.example.pkmedical.Event.MessageWrap;
import com.example.pkmedical.R;
import com.example.pkmedical.Utils.CommandUtil;
import com.example.pkmedical.Utils.DistinguishUtil;
import com.example.pkmedical.Utils.SPUtils;
import com.example.pkmedical.Utils.SerialProtUtil;
import com.example.pkmedical.Utils.TimeUtils;
import com.raizlabs.android.dbflow.config.FlowManager;
import com.raizlabs.android.dbflow.sql.language.SQLite;
import com.raizlabs.android.dbflow.structure.ModelAdapter;

import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;

import static com.example.pkmedical.Utils.NumberUtil.byteToInteger;

public class WeightPineBedActivity extends BaseActivity {
    private static final String TAG = "yangshuo";
    String one, two, three, four, five;
    String mIntWeight;
    byte[] mBytes;
    @BindView(R.id.releasezero_twotext)
    TextView releasezeroTwotext;
    private int numType = 0;
    private int mJumpType;
    long needDelId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_weightpinebed);
        ButterKnife.bind(this);
    }

    @Override
    public void initData() {
//        SerialProtUtil.getInstance().sendBytes2(2, CommandUtil.GET_WEIGHT);
        TimeCount();
    }

    @Override
    public void initView() {
        Intent intent = getIntent();
        if (null != intent) {
            mJumpType = intent.getIntExtra("jumpYtpe", 0);
        }
    }

    @Override
    public void onReceiveEvent(MessageWrap event) {
        super.onReceiveEvent(event);
        if (event.getCode() == MessageWrap.WEIGHT_SHOW) {
            Log.d(TAG, "onDataReceivedPingBed [ byte[] ]: " + Arrays.toString(event.getBytes()));
            mBytes = event.getBytes();
            distinguish(mBytes);
        } else {
            Log.d(TAG, "onDataReceivedPingBed [ byte[] ]: NoThisData");
        }
    }

    /**
     * 返回数据识别
     */
    private void distinguish(byte[] bytes) {
        if (DistinguishUtil.distinguishUtil(bytes)) {
            switch (bytes[3]) {
                case 5:
                    five = bytes[4] + "." + bytes[5];
                    break;
            }
        } else {
        }
        int aaa;
        int bbb;
        aaa = byteToInteger(bytes[4]);
        bbb = byteToInteger(bytes[5]);
        mIntWeight = aaa + "." + bbb;
        if (null != mIntWeight) {
            switch (mJumpType) {
                case 0:
                    CommandUtil.ADD_PLUS_TYPE = 0;
                    JumpWeight();
                    break;
                case 1:
                    CommandUtil.ADD_PLUS_TYPE = 1;
                    JumpWeight();
//                    JumpAdd();
                    break;
            }

        }

    }

    private void addDatas() {
        SPUtils.getInstance().put("defultWeight", mIntWeight);
        WeightData weightData = new WeightData();
        ModelAdapter<WeightData> adapter = FlowManager.getModelAdapter(WeightData.class);
        List<WeightData> list = SQLite.select().from(WeightData.class).queryList();
        if (list.size() > 6) {
            needDelId = list.get(0).id;
            //方法二 直接删除
            SQLite.delete(WeightData.class)
                    .where(WeightData_Table.id.eq(needDelId))
                    .execute();
        } else {

        }
        weightData.id = CommandUtil.WEIGHT_DESTORY_ID;//这一行必须加，必须指定id，后面才能根据id修改某一条的数据
        String mDate = SPUtils.getInstance().getString("Last_time");
        String str=mDate.substring(5);
        weightData.date = str;
        weightData.weight = Float.parseFloat(mIntWeight);
        adapter.insert(weightData);//插入
        CommandUtil.WEIGHT_DESTORY_ID++;
    }

    /**
     * byte转char
     */


    @Override
    protected boolean isRegisteredEventBus() {
        return true;
    }

    @Override
    public void initPresenter() {

    }

    @Override
    public void showDialog(String... msg) {

    }

    private void JumpWeight() {
        switch (CommandUtil.ADD_PLUS_TYPE) {
            case 0:
                onlyPerson();
                break;
            case 1:
                addThings();
                break;
//            case 2:
//                SPUtils.getInstance().put("user_difference_weight", 0);
//                break;
        }

    }

    private void JumpAdd() {
        startActivity(new Intent(MyApp.getAppContext(), OptionAddContinueActivity.class));
        WeightPineBedActivity.this.finish();
    }

    private void onlyPerson() {

        double mWeight;
        mWeight = Double.parseDouble(mIntWeight);
        if (mWeight < 30) {
            numType = 1;
        } else if (mWeight > 225) {
            numType = 2;
        } else {
            numType = 0;
        }
        if (numType == 0) {
            if (CommandUtil.IS_FIRST) {
                SPUtils.getInstance().put("Initial_time", TimeUtils.getNowDataAll());
                SPUtils.getInstance().put("user_first_weight", mIntWeight);
                SPUtils.getInstance().put("user_now_weight", mIntWeight);
                CommandUtil.IS_FIRST = false;
            }
            SPUtils.getInstance().put("Last_time", TimeUtils.getNowDataAll());
            SPUtils.getInstance().put("user_last_weight", SPUtils.getInstance().getString("user_now_weight"));
            SPUtils.getInstance().put("user_now_weight", mIntWeight);
            addDatas();
            startActivity(new Intent(MyApp.getAppContext(), NewUserWeightActivity.class));
            WeightPineBedActivity.this.finish();
        } else {
            Intent intent = new Intent();
            intent.putExtra("small_or_big", numType);//1:太小，2：太大,0:正常
            intent.setClass(MyApp.getAppContext(), WeightGoBeyondActivity.class);
            startActivity(intent);
            WeightPineBedActivity.this.finish();
        }
    }

    private void addThings() {
        double MyWeight;
        MyWeight = Double.parseDouble(mIntWeight);
        SPUtils.getInstance().put("user_difference_weight_one", MyWeight + "");
        if (MyWeight < 30) {
            numType = 1;
        } else if (MyWeight > 225) {
            numType = 2;
        } else {
            numType = 0;
        }
        if (numType == 0) {
            JumpAdd();
//            startActivity(new Intent(MyApp.getAppContext(), NewUserWeightActivity.class));
//            WeightPineBedActivity.this.finish();
        } else {
            Intent intent = new Intent();
            intent.putExtra("small_or_big", numType);//1:太小，2：太大,0:正常
            intent.setClass(MyApp.getAppContext(), WeightGoBeyondActivity.class);
            startActivity(intent);
            WeightPineBedActivity.this.finish();
        }
    }

    private int timeLong = 4;
    private Disposable mTimeCountDisposable;

    /**
     * 倒计时
     */
    public void TimeCount() {
        if (mTimeCountDisposable != null) {
            //取消上一次的订阅
            mTimeCountDisposable.dispose();
        }
//        //0-count依次输出，延时0s执行，每1s发射一次。
        mTimeCountDisposable = Flowable.intervalRange(4, 4, 0, 1, TimeUnit.SECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .doOnNext(aLong -> {
                    timeLong -= 1;
                    releasezeroTwotext.setText(timeLong + "秒后称量患者体重");
                })
                .doOnComplete(() -> {
                    if (mTimeCountDisposable != null) {
                        mTimeCountDisposable.dispose();
                    }
                    SerialProtUtil.getInstance().sendBytes200(2, CommandUtil.GET_WEIGHT);
                })
                .subscribe();
    }
}
